package cn.jcet.gumall.product.service.impl;

import cn.jcet.common.to.SkuReductionTo;
import cn.jcet.common.utils.R;
import cn.jcet.gumall.product.entity.*;
import cn.jcet.gumall.product.feign.CouponFeignService;
import cn.jcet.gumall.product.service.*;
import cn.jcet.common.to.SpuBoundsTo;
import cn.jcet.gumall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jcet.common.utils.PageUtils;
import cn.jcet.common.utils.Query;

import cn.jcet.gumall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService infoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo saveVo) {
        //1、保存spu基本信息：pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(saveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseInfo(spuInfoEntity);

        //2、保存spu的描述信息：pms_spu_info_desc
        List<String> decript = saveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        this.infoDescService.saveInfoDesc(spuInfoDescEntity);

        //3、保存spu图片集：pms_spu_images
        List<String> images = saveVo.getImages();
        this.spuImagesService.saveImages(spuInfoEntity.getId(),images);


        //4、保存spu规格参数：pms_product_attr_value
        List<BaseAttrs> baseAttrs = saveVo.getBaseAttrs();
        // map映射
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(item.getAttrId());
            // 根据id查询
            AttrEntity attrEntity = this.attrService.getById(item.getAttrId());
            attrValueEntity.setAttrName(attrEntity.getAttrName());
            attrValueEntity.setAttrValue(item.getAttrValues());
            attrValueEntity.setQuickShow(item.getShowDesc());
            attrValueEntity.setSpuId(spuInfoEntity.getId());
            return attrValueEntity;
        }).collect(Collectors.toList());
        this.productAttrValueService.saveProductBatch(collect);

        // 5、保存spu积分信息：跨库 gulimall_sms ->sms_spu_bounds
        Bounds bounds = saveVo.getBounds();
        // 积分实体
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        // 保存
        R r = this.couponFeignService.saveBatchBounds(spuBoundsTo);

        if (r.getCode() != 0){
            log.error("远程服务保存积分信息失败");
        }

        // 6、保存当前spu对于的所有sku信息
        // 6.1）、sku的基本信息：pms_sku_info
        List<Skus> skus = saveVo.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach(item ->{
                String defaultImages = "";

                for (Images img : item.getImages()) {
                    if (img.getDefaultImg() == 1){
                        defaultImages = img.getImgUrl();
                    }
                }
                // sku基本属性
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImages);

                // 保存sku
                this.skuInfoService.saveBatchInfo(skuInfoEntity);
                // skuid
                Long skuId = skuInfoEntity.getSkuId();
                //6.2）、sku的图片信息：pms_sku_images
                List<SkuImagesEntity> collect1 = item.getImages().stream().map(imgs -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setImgUrl(imgs.getImgUrl());
                    skuImagesEntity.setDefaultImg(imgs.getDefaultImg());
                    skuImagesEntity.setSkuId(skuId);
                    return skuImagesEntity;
                }).filter(entity ->{
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                // 保存图片
                this.skuImagesService.saveBatch(collect1);

                //6.3）、sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> collect2 = attr.stream().map(attrs -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attrs, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                this.skuSaleAttrValueService.saveBatch(collect2);

                //6.4)、sku的优惠、减满等信息：gulimall_sms-》sku_ladder/
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1){
                    // 调用远程接口
                    R r1 = this.couponFeignService.saveSkuInfo(skuReductionTo);
                    if (r1.getCode() != 0){
                        log.error("远程服务保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondtion(Map<String, Object> params) {

        /**
         * brandId: 0
         * catelogId: 0
         * key: ""
         * status: ""
         */
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 获取key
        String key = (String) params.get("key");

        // 模糊匹配操作
        if (!StringUtils.isEmpty(key)){
            wrapper.and(item ->{
                item.eq("id",key).or()
                        .like("spu_name",key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catalog_id = (String) params.get("catalog_id");
        if(!StringUtils.isEmpty(catalog_id)&& !"0".equalsIgnoreCase(catalog_id)){
            wrapper.eq("catalog_id",catalog_id);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
               wrapper
        );

        return new PageUtils(page);
    }
}